<template>
  <el-card>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>更改密码</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form
    :model="form"
    :rules="rules"
      ref="form"
      label-width="90px"
      style="width: 500px; margin-top: 30px"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="form.old_pwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="form.new_pwd"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="re_pwd">
        <el-input v-model="form.re_pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePwd">修改密码</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { reqResetPwd } from '@/api/user'

export default {
  name: 'ResetPwd',
  data () {
    const validateNewPwd = (rule, value, callback) => {
      if (value !== this.form.old_pwd) {
        callback()
      } else {
        callback(new Error('新旧密码不能一致'))
      }
    }
    const validateRePwd = (rule, value, callback) => {
      if (value === this.form.new_pwd) {
        callback()
      } else {
        callback(new Error('两次密码不一致'))
      }
    }
    return {
      form: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '原密码不为空', trigger: ['change', 'blur'] },
          { pattern: /^\S{6,15}$/, message: '原密码6-15非空', trigger: ['change', 'blur'] }
        ],
        new_pwd: [
          { required: true, message: '原密码不为空', trigger: ['change', 'blur'] },
          { pattern: /^\S{6,15}$/, message: '原密码6-15非空', trigger: ['change', 'blur'] },
          { validator: validateNewPwd, trigger: ['change', 'blur'] }
        ],
        re_pwd: [
          { required: true, message: '原密码不为空', trigger: ['change', 'blur'] },
          { pattern: /^\S{6,15}$/, message: '原密码6-15非空', trigger: ['change', 'blur'] },
          { validator: validateRePwd, trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  methods: {

    reset () {
      this.$refs.form.resetFields()
    },
    updatePwd () {
      this.$refs.form.validate(async (flag) => {
        if (!flag) return console.log('校验失败')
        const { data } = await reqResetPwd(this.form)
        if (data.code !== 0) return this.$message.error(data.message)
        this.$message.success(data.message)

        localStorage.removeItem('token')
        this.$router.push('/login')
      })
    }
  }

}
</script>

<style></style>
